package com.xnyzc.lhy.task.fallback.order;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xnyzc.lhy.common.constant.MqConstant;
import com.xnyzc.lhy.common.util.DateUtil;
import com.xnyzc.lhy.common.util.XieChengUtil;
import com.xnyzc.lhy.common.util.http.HttpRequestUtil;
import com.xnyzc.lhy.mis.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.task.entity.demo.OrderDetailRequest;
import com.xnyzc.lhy.task.entity.demo.OrderDetailResponse;
import com.xnyzc.lhy.task.fegin.order.FlightOrderService;
import com.xnyzc.lhy.task.mapper.sys.OaCOrderPersonalMapper;
import com.xnyzc.lhy.task.mq.MQProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class FlightOrderServiceImpl implements FlightOrderService {
    @Autowired
    private OaCOrderPersonalMapper oaCOrderPersonalMapper;
    @Autowired
    private MQProducer mqProducer;
    //供应商ID
    @Value("${global.xc.venderId}")
    private String venderId;

    //渠道
    @Value("${global.xc.channel}")
    private String channel;

    //版本
    @Value("${global.xc.version}")
    private String version;

    //携程密钥
    @Value("${global.xc.secretKey}")
    private String secretKey;

    @Value("${global.xc.callback}")
    private String callback;


    @Override
    public void flightOrder() {
        Date date = DateUtil.dateAddMinutes(new Date(), 120);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        QueryWrapper<OaCOrderPersonal> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaCOrderPersonal.ORDER_CHANNEL, 3);
        queryWrapper.lt(OaCOrderPersonal.APPOINTMENT, date);
        queryWrapper.in(OaCOrderPersonal.ORDER_STATUS, 3, 4, 5);
        queryWrapper.eq(OaCOrderPersonal.ORDER_TYPE, 3);
        List<OaCOrderPersonal> oaCOrderPersonals = oaCOrderPersonalMapper.selectList(queryWrapper);
        try {
            for (int i = 0; i < oaCOrderPersonals.size(); i++) {
                OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonals.get(i);
                String orderNo = oaCOrderPersonal.getOrderNo();
                String personalId = oaCOrderPersonal.getPersonalId().toString();
                OrderDetailRequest request = new OrderDetailRequest();
                request.setCtripPurchaseOrderID(Long.parseLong(orderNo));
                request.setVendorOrderID(personalId);
                String res = sendToXC(oaCOrderPersonal.getOrderNo(), JSON.toJSONString(request));
                OrderDetailResponse response = JSON.parseObject(res, OrderDetailResponse.class);
                if (response != null && "OK".equalsIgnoreCase(response.getMsgCode())) {
                    if (response.getOrderDetailRuleDO()==null){
                        continue;
                    }
                    String sysExpectBookTime = response.getOrderDetailRuleDO().getSysExpectBookTime();
                    if (sysExpectBookTime != null) {
                        if (oaCOrderPersonal.getRealFlightTime() == null || !(oaCOrderPersonal.getRealFlightTime().getTime()==sdf.parse(sysExpectBookTime).getTime())) {
                            oaCOrderPersonal.setRealFlightTime(sdf.parse(sysExpectBookTime));
                            int i1 = oaCOrderPersonalMapper.updateById(oaCOrderPersonal);
                            if (oaCOrderPersonal.getAppointment().equals(sdf.parse(sysExpectBookTime))){
                                continue;
                            }
                            if (i1 > 0) {
                                mqProducer.sendMsg(oaCOrderPersonal, MqConstant.FLIGHT_ORDER, null);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取航班时间信息异常：\n",e);
            e.printStackTrace();
        }
        return;
    }

    private String sendToXC(String orderId, String body) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String timeStamp = sdf.format(System.currentTimeMillis());
        log.info("XC-" + body);
        String params = "";
        String action = "order/detail";
        try {
            params = XieChengUtil.encodeDES(secretKey, body);
            params = params.toUpperCase();
        } catch (Exception e) {
            log.info("sendToXC-"+"消息加密失败！");
            e.printStackTrace();
            return null;
        }
        String sign = XieChengUtil.getCallbackSign(venderId, timeStamp, params.length(), secretKey);
        String url = callback + "/" + channel + "-" + venderId + "/" + action + "/" + version + "/" + orderId + "/" + timeStamp + "/" + sign;
        String result = null;
        try {
            result = HttpRequestUtil.requestPostJson(url, params);
        } catch (IOException e) {
            log.info("sendToXC-"+"携程接口请求异常："+action);
            e.printStackTrace();
        }
        return result;
    }
}
